package com.jiazhong.example.project.shoppingcart.service.impl;

import com.jiazhong.example.project.shoppingcart.bean.Users;
import com.jiazhong.example.project.shoppingcart.mapper.UsersMapper;
import com.jiazhong.example.project.shoppingcart.service.UsersService;
import com.jiazhong.example.project.shoppingcart.util.JsonResult;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.http.HttpSession;
import java.io.InputStream;

public class UsersServiceImpl implements UsersService {

    private UsersMapper usersMapper;
    private SqlSession session;
    private SqlSessionFactory ssf;

    public UsersServiceImpl() {
        InputStream inputStream = UsersServiceImpl.class.getClassLoader().getResourceAsStream("config.xml");
        ssf = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Override
    public JsonResult save(Users users) {
        session = ssf.openSession(true);
        usersMapper = session.getMapper(UsersMapper.class);
        int row = 0;
        try {
            row = usersMapper.save(users);
        } catch (Exception e) {
            return new JsonResult(500, "录入失败");
        }

        if (row == 0) {
            return new JsonResult(500, "录入失败");
        }
        return new JsonResult("录入成功");
    }

    @Override
    public JsonResult checkUsername(String username) {
        session = ssf.openSession(true);
        usersMapper = session.getMapper(UsersMapper.class);
        int row = usersMapper.checkUsername(username);
        if (row == 0) {
            return new JsonResult("账号可以使用");
        }
        return new JsonResult(501, "账号已被占用");
    }

    @Override
    public JsonResult checkPhone(String phone) {
        session = ssf.openSession(true);
        usersMapper = session.getMapper(UsersMapper.class);
        int row = usersMapper.checkPhone(phone);
        if (row == 0) {
            return new JsonResult("手机号可以使用");
        }
        return new JsonResult(502, "手机号已被占用");
    }

    @Override
    public JsonResult login(String username, String password, HttpSession session) {
        this.session = ssf.openSession(true);
        usersMapper = this.session.getMapper(UsersMapper.class);
        Users users = usersMapper.login(username, password);
        if (users == null) {
            return new JsonResult(500, "账号或者密码错误");
        }
        session.setAttribute("user", users);
        return new JsonResult(users);
    }
}
